package org.hbhk.hms.service.impl;

import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.exceptions.PersistenceException;
import org.hbhk.hms.entity.HmsTopic;
import org.hbhk.hms.mapper.HmsTopicMapper;
import org.hbhk.hms.service.IHmsTopicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;

@Service
public class HmsTopicService implements IHmsTopicService {

	@Autowired
	private HmsTopicMapper hmsTopicMapper;

	private IdentifierGenerator identifierGenerator = new DefaultIdentifierGenerator();

	@Autowired
	private SqlUtil sqlUtil;

	@Autowired

	private JdbcTemplate jdbcTemplate;

	private Logger log = LoggerFactory.getLogger(getClass());

	@Override
	@Transactional
	public int insert(HmsTopic entity) {

		return hmsTopicMapper.insert(entity);
	}

	@Override
	public int insertBatch(List<HmsTopic> entitys) {

		for (HmsTopic hmsTopic : entitys) {
			Number number = identifierGenerator.nextId(hmsTopic);
			Long id = number.longValue();
			hmsTopic.setId(id);
		}
		try {
			sqlUtil.executeInsert(jdbcTemplate, "hms_topic", entitys);
		} catch (Exception e) {
			log.error(" batch error ", e);
			// 执行批量插入 唯一性失败，走单个输入
			for (HmsTopic hmsTopic : entitys) {
				try {
					insert(hmsTopic);
				} catch (DuplicateKeyException | PersistenceException e1) {
					log.error("消费错误日志", e1);
					String exceMess = ExceptionUtils.getStackTrace(e1);
					// 特殊异常要返回错误
					if (exceMess.contains("MySQLIntegrityConstraintViolationException")) {
						// 主键冲突异常-不忽略
						if (exceMess.contains("PRIMARY")) {
							throw e1;
						}
						// 非唯一索引异常-不忽略
						if (!exceMess.contains("Duplicate entry")) {
							throw e1;
						}
					}
				}
			}

		}
		return 0;
	}

}
